//
//  ASMyWorkListVC.m
//  AvatarShow
//
//  Created by xunruiIOS on 2021/5/6.
//

#import "ASMyWorkListVC.h"
#import "ASNoneView.h"
#import "ASPhotoModel.h"
#import "ASHomeMainCell.h"
#import "ASDownLoadDetailVC.h"

@interface ASMyWorkListVC () <UICollectionViewDelegate, UICollectionViewDataSource>

@property (strong, nonatomic) NSMutableArray *dataArr;
@property (strong, nonatomic) UICollectionView *collectionView;
@property (strong, nonatomic) ASNoneView *noneView;
@property (assign, nonatomic) BOOL ifPhotoSucceed;             ///是否读取相册成功

@end

@implementation ASMyWorkListVC

- (void)dealloc{
    FELog(@"ASMyWorkListVC释放");
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"我的作品";
    self.view.backgroundColor = BACKGROUND_COLOR;
    [self.view addSubview:self.collectionView];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    [self vanFindPhone:YES];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(reloadPhotoData) name:@"ReloadDownLoadData" object:nil];
    // Do any additional setup after loading the view.
}

///判断是否可以读取相册数据
- (void)vanFindPhone:(BOOL)ifHUD{
    [ASTool canSeePhotoCompletion:^(BOOL isSucceed, PHAuthorizationStatus photoType) {
        if (isSucceed) {
            self.ifPhotoSucceed = isSucceed;
            [self createAllData:ifHUD];
        }
    }];
}

///更新相册数据
- (void)reloadPhotoData{
    if (self.ifPhotoSucceed) {
        [self createAllData:NO];
    }else{
        [MBProgressHUD showError:@"相册读取失败"];
    }
}

///读取相册数据
- (void)createAllData:(BOOL)ifHUD{
    if (ifHUD) {
        [MBProgressHUD showMessage:@"加载中..."];
    }
    [self.dataArr removeAllObjects];
    self.dataArr = [NSMutableArray new];

    @weakify(self);
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        @strongify(self);
         PHFetchOptions *option = [[PHFetchOptions alloc] init];
         option.predicate = [NSPredicate predicateWithFormat:@"mediaType == %ld",
                             PHAssetMediaTypeImage];
         option.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];
       
        // 我的照片流 1.6.10重新加入..
         PHFetchResult *topLevelUserCollections = [PHCollectionList fetchTopLevelUserCollectionsWithOptions:nil];
         NSArray *allAlbums = @[topLevelUserCollections];
         for (PHFetchResult *fetchResult in allAlbums) {
             for (PHAssetCollection *collection in fetchResult) {
                 // 有可能是PHCollectionList类的的对象，过滤掉
                 if (![collection isKindOfClass:[PHAssetCollection class]]) continue;
                 NSString *title = [NSString stringWithFormat:@"%@(制作)",[ASTool appName]];
        
                 if ([collection.localizedTitle isEqualToString:title]) {
                     PHFetchResult *fetchResult = [PHAsset fetchAssetsInAssetCollection:collection options:option];
                     [fetchResult enumerateObjectsUsingBlock:^(PHAsset *asset, NSUInteger idx, BOOL * _Nonnull stop) {
                         dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
                         ASPhotoModel *model = [ASPhotoModel new];
                         model.asset = asset;
                         [[PHImageManager defaultManager]requestImageDataForAsset:asset options:nil resultHandler:^(NSData * _Nullable imageData, NSString * _Nullable dataUTI, UIImageOrientation orientation, NSDictionary * _Nullable info) {
                             UIImage * image = [UIImage imageWithData:imageData];
                             model.showImage = image;
                             [self.dataArr insertObject:model atIndex:0];
                             dispatch_semaphore_signal(semaphore);
                         }];
                         dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
                     }];
                 }
                NSLog(@"sdafasdfasdfadsf====%@",collection.localizedTitle);
             }
         }
            dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD hideHUD];
                [self.collectionView reloadData];
            });
        });
}


- (UICollectionView *)collectionView{
    if (!_collectionView) {
        UICollectionViewFlowLayout *fl = [UICollectionViewFlowLayout new];
        fl.minimumLineSpacing = 7;
        fl.minimumInteritemSpacing = 7;
        fl.sectionInset = UIEdgeInsetsMake(13, 13, 13, 13);
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:fl];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor = self.view.backgroundColor;
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.alwaysBounceVertical = YES;
        [_collectionView registerClass:[ASHomeMainCell class] forCellWithReuseIdentifier:ASHomeMainCellStr];
        [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"UICollectionViewCellNone"];
    }
    return _collectionView;
}

- (ASNoneView *)noneView{
    if (!_noneView) {
        _noneView = [[ASNoneView alloc]initWithFrame:CGRectZero];
        [_noneView.logoImage setImage:[UIImage imageNamed:@"me_wsj"]];
        _noneView.titleLab.text = @"没有发现相关内容...";
    }
    return _noneView;
}

#pragma mark - UICollectionViewDelegate
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dataArr.count>0?self.dataArr.count:1;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (self.dataArr.count > 0) {
        return CGSizeMake((SCREEN_WIDTH - 33)/2, (SCREEN_WIDTH - 33)/2);
    }
    return CGSizeMake(SCREEN_WIDTH, SCREENH_HEIGHT-Height_NavBar-60);
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (self.dataArr.count > 0) {
        ASHomeMainCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ASHomeMainCellStr forIndexPath:indexPath];
        if (self.dataArr.count > indexPath.row) {
            cell.photoModel = self.dataArr[indexPath.row];
        }
        return cell;
    }else{
        UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"UICollectionViewCellNone" forIndexPath:indexPath];
        for (UIView *subV in cell.contentView.subviews) {
            if ([subV isKindOfClass:[ASNoneView class]]) {
                [subV removeFromSuperview];
            }
        }
        [cell.contentView addSubview:self.noneView];
        [self.noneView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_equalTo(UIEdgeInsetsMake(-50, 0, 0, 0));
        }];
        return cell;
    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (self.dataArr.count > 0) {
        [self pushDownLoadImageVC:indexPath];
    }
}

- (void)pushDownLoadImageVC:(NSIndexPath *)indexPath{
    ASDownLoadDetailVC *detailVC = [ASDownLoadDetailVC new];
    detailVC.hidesBottomBarWhenPushed = YES;
    [detailVC createOldArr:self.dataArr showIndex:indexPath.row];
    detailVC.type = 0;
    [self.navigationController pushViewController:detailVC animated:YES];

}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
